package service;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import domain.CreditCard;
import domain.Person;

@Service("personService")
@Transactional
public class PersonService {
	protected static Logger log = Logger.getLogger(PersonService.class);

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	public List<Person> getAll() {
		log.info("Retriving all persons");
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM PERSON");
		return query.list();
	}

	public Person getPersonById(int id) {
		log.info("Retriving get a person by id");
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM Person p left join fetch p.creditCards where p.id=:id");
		query.setParameter("id", id);
		return (Person) query.uniqueResult();
	}

	public void addPerson(Person person) {
		log.info("Adding a new person");
		Session session = sessionFactory.getCurrentSession();
		session.save(person);
	}

	public void deletePerson(int id) {
		log.info("Retriving to delete a person id : " + id);
		Session session = sessionFactory.getCurrentSession();
		Person person = getPersonById(id);
		Set<CreditCard> creditCards = person.getCreditCards();
		for (CreditCard c : creditCards) {
			session.delete(c);
		}
	}

	public void editPerson(Person person) {
		log.info("Retriving to edit a person :" + person.getFirstName());
		Session session = sessionFactory.getCurrentSession();
		Person existPerson = getPersonById(person.getId());
		existPerson.setFirstName(person.getFirstName());
		existPerson.setLastName(person.getLastName());
		existPerson.setAddress(person.getAddress());
		existPerson.setAge(person.getAge());
		session.save(existPerson);
	}

}
